import GlobalSotre from '../../global.store';
import {observable, action, runInAction} from 'mobx';
import {writeCookie, getToken, getCookie, deleteCookie} from '../../common/cookies';
import fetch from '../../common/fetch';

const security = '/security', version = '/api/v1';
const api = {
  login: `${security}${version}/users/login?projectNo=appbricks`,
  getUser: (id, query) => `${security}${version}/users/${id}?${query}`,
};

export default class LoginStore extends GlobalSotre{
  @observable loginState = false;

  // 页面初始化，判断有没有登录，如果有登陆直接跳主页
  @action init = () => {
    let token = getCookie('token');
    this.setLoginState(!!token);
  }

  @action setLoginState = (flag) => {
    this.loginState = flag;
  }

  // 退出登录处理
  @action logout = () => {
    this.loginState = false;
    deleteCookie('id');
    deleteCookie('token');
    deleteCookie('projects');
    deleteCookie('projectName');
  }

  // 登录操作，根据不同的返回信息判断登录情况，1:用户名密码错误，2:获取用户信息失败，0:成功
  @action login = async (data) => {
    this.openLoading()
    // 执行登录请求
    let loginRes;
    try{
      loginRes = await fetch.post(api.login, data);
    }catch(err) {
      this.closeLoading();
      return 1;
    }
    let id = loginRes.payload.id;
    let token = loginRes.payload.key;
    writeCookie('id', id);
    writeCookie('token', token);

    // 请求用户信息
    let query = `?token=${token}&timestamp=${+Date.now()}`;
    let userRes;
    try {
      userRes = await fetch.get(api.getUser(id, query));
    }catch(err) {
      this.closeLoading();
      return 2;
    }
    writeCookie('projects', userRes.payload.currentProjectNo);
    writeCookie('projectName', userRes.payload.currentProjectName);

    this.closeLoading();
    this.loginState = true;
    return 0;
  }
}